package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmeaDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmeaDishMapper setmeaDishMapper;
    @Autowired
    private SetmealMapper setmealMapper;


    /**
     * 新增菜品和对应口味
     *
     * @param dishDTO
     * @return
     */
    //开始事务
    @Transactional
    @Override
    public void saveWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        //向菜品表插入1条数据
        dishMapper.insert(dish);
        //能自动获取插入后的id
        Long dishId = dish.getId();
        //取出口味信息
        List<DishFlavor> flavors = dishDTO.getFlavors();

        if (flavors != null && flavors.size() > 0) {
            //给每个口味插入id,并插入到口味表里
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishId);
                dishFlavorMapper.insert(dishFlavor);
            });
        }
    }

    /**
     * 菜品分页查询
     *
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult page(DishPageQueryDTO dishPageQueryDTO) {
        QueryWrapper<Dish> wrapper = new QueryWrapper<>();
        //判断查询菜单名是否为空，为空就不加判断条件
        if (dishPageQueryDTO.getName() != null) {
            wrapper.like("name", dishPageQueryDTO.getName());
        }
        //判断查询菜单分类是否为空，为空就不加判断条件
        if (dishPageQueryDTO.getCategoryId() != null) {
            wrapper.eq("category_id", dishPageQueryDTO.getCategoryId());
        }
        //判断查询菜单是否被禁用，为禁用就不加判断条件
        if (dishPageQueryDTO.getCategoryId() != null) {
            wrapper.eq("status", dishPageQueryDTO.getStatus());
        }
        Page<Dish> page = new Page<>(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        dishMapper.selectPage(page, wrapper);
        return new PageResult(page.getTotal(), page.getRecords());
    }

    /**
     * 菜品批量删除
     *
     * @param ids
     * @return
     */
    @Override
    public void delete(List<Long> ids) {
        //判断当前菜品是否能够删除---是否存在起售中的菜品??
        for (Long id : ids) {
            Dish dish = dishMapper.selectById(id);
            if (dish != null && dish.getStatus() == StatusConstant.ENABLE) {
                //当前菜品处于起售中，不能删除
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
        //判断当前菜品是否能够删除---是否被套餐关联了??
        List<SetmealDish> setmealDishes = setmeaDishMapper.selectBatchIds(ids);
        if (setmealDishes != null && setmealDishes.size() > 0) {
            //当前菜品被套餐关联了，不能删除
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //删除菜品天中的菜品数据
        ids.forEach(id -> {
            //删除菜品与口味表的记录
            dishMapper.deleteById(id);
            QueryWrapper<DishFlavor> wrapper = new QueryWrapper<>();
            wrapper.eq("dish_id", id);
            dishFlavorMapper.delete(wrapper);
        });
    }

    /**
     * 根据id查询菜品
     *
     * @param id
     * @return
     */
    @Override
    public DishVO getByIdWithFlavor(Long id) {
        //根id查询菜品数据
        Dish dish = dishMapper.selectById(id);
        //根据菜品id查询囗味数据
        QueryWrapper<DishFlavor> qw = new QueryWrapper<>();
        qw.eq("dish_id", id);
        List<DishFlavor> dishFlavors = dishFlavorMapper.selectList(qw);
        // 将查询到的数据封装到N0
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(dishFlavors);
        return dishVO;
    }


    /**
     * 修改菜品
     *
     * @param dishDTO
     * @return
     */
    public void update(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        QueryWrapper<Dish> wrapper = new QueryWrapper<>();
        wrapper.eq("id",dish.getId());
        //修改菜品表基本信息
        dishMapper.update(dish, wrapper);
        //删除原有的口味数据
        dishFlavorMapper.deleteById(dishDTO.getId());
        //重新插入口味数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishDTO.getId());
                //向口味表插入条数据
                dishFlavorMapper.insert(dishFlavor);
            });
        }
    }

    /**
     * todo
     * 菜品起售停售
     *
     * @param status
     * @param id
     */
    @Transactional
    public void startOrStop(Integer status, Long id) {
        if (status == StatusConstant.DISABLE || status==StatusConstant.ENABLE) {
            //修改菜单的起售值
            QueryWrapper<Dish> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("id",id);
            Dish dish = Dish.builder()
                    .status(status)
                    .build();
            dishMapper.update(dish, wrapper1);
            //在套餐与菜单表中取出套餐的id
            List<Long> setmealIds = new ArrayList<>();
            QueryWrapper<SetmealDish> qw = new QueryWrapper<>();
            qw.eq("dish_id", id);
            qw.select("setmeal_id");
            List<SetmealDish> setmealDishes = setmeaDishMapper.selectList(qw);
            //根据id修改起售值
            if (setmealDishes != null && setmealDishes.size() > 0) {
                setmealDishes.forEach((SetmealDish setmealDish) -> {
                    //todo 未能解决是起售但是其他的菜品是禁售这个套餐也是禁售
                    //if (status==StatusConstant.DISABLE){
                        Setmeal setmeal = Setmeal.builder()
                                .status(status)
                                .build();
                        QueryWrapper<Setmeal> wrapper = new QueryWrapper<>();
                        wrapper.eq("id", setmealDish.getSetmealId());
                        setmealMapper.update(setmeal, wrapper);
                });
            }
        }
    }

    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    public List<Dish> list(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();

//        QueryWrapper<Dish> wrapper = new QueryWrapper<>();
//        wrapper.eq("category_id",categoryId);
//        wrapper.eq("status",StatusConstant.ENABLE);
//        wrapper.like("name",name);
        return dishMapper.list(dish);
    }

    /**
     *用户
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);
        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            QueryWrapper<DishFlavor> wrapper = new QueryWrapper<>();
            wrapper.eq("dish_id",d.getId());
            List<DishFlavor> flavors = dishFlavorMapper.selectList(wrapper);

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}



